package ext.tianma.bom.workflow;

/**
 * @author 魏文杰
 */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import wt.fc.ObjectReference;
import wt.fc.collections.WTArrayList;
import wt.fc.collections.WTCollection;
import wt.lifecycle.State;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartSubstituteLink;
import wt.part.WTPartUsageLink;
import wt.util.WTException;
import wt.vc.config.ConfigException;
import wt.vc.wip.WorkInProgressHelper;
import ext.com.core.CoreUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.generic.erp.util.BOMStructureUtil;
import ext.tianma.part.forms.TMTypeUtil;

public class ReWriteBOMReviewConfirmBusiness {
	//新品状态
	private static final String NEW_PRODUCT = "NewProduct" ;
	
	//量产发布
	private static final String MASS_PRODUCTION_RELEASE = "MassProductionRelease" ;
	
	//批准
	private static final String APPROVAL = "APPROVAL" ;
	
	private static final String INWORK = "INWORK" ;
	
	private static final String D_VIEWS = "Design";
	
	private static List<String> list = new ArrayList<String>();
	
	static{
		list.add(INWORK);
		list.add(APPROVAL);
		list.add(NEW_PRODUCT);
		list.add(MASS_PRODUCTION_RELEASE);
	}
	
	public static void showPageData(Object pbo , WTArrayList reviewObjs , WTArrayList  inconformityReviewObjs) throws WTException{
		
    	if(pbo == null || !(pbo instanceof WTPart)){
    		System.out.println("传入进来的对象"+pbo+"为空或者不是【WTDocument】类型的对象，直接返回空！");
    		return ;
    	}  	
    	
    	WTPart pboPart = (WTPart) pbo;
	    
    	List<WTPart> allPart = new ArrayList<WTPart>();
    	
    	//将PBO零部件加入List
	    //allPart.add( pboPart );
	    
	 	//递归获得所有的子部件
	    List<WTPart> allSubPart = getAllSubPartsWithSubstitute( pboPart ) ;
	    
    	//System.out.println("指定对象【"+pboPart.getDisplayIdentifier()+"】下包含的所有子部件个数是："+allSubPart.size());
    	
    	//将所有子件加入List
    	allPart.addAll(allSubPart);
		    	
    	//初始化传入来的两个参数 
    	if(reviewObjs == null){
    		reviewObjs = new WTArrayList();
    	}else{
    		reviewObjs.clear();
    	}
    	
		if(inconformityReviewObjs == null){
			inconformityReviewObjs = new WTArrayList();	
		}else{
			inconformityReviewObjs.clear();
		}
		
		reviewObjs.add( pboPart );
		
		checkAllParts( allPart , reviewObjs , inconformityReviewObjs ) ;
	    
		checkPartDesignSate( pboPart , reviewObjs , inconformityReviewObjs );
		//checkPartsIsCheckOut( allPart ) ;
		
	}

	/**
	 * 检查列表中的零部件，是否有被检出的零部件
	 * 
	 * @param parts
	 * @throws WTException
	 */
	public static void checkPartsIsCheckOut( List<WTPart> parts ) throws WTException {
		//保存被检出部件的编号
		StringBuffer checkoutInfo = new StringBuffer("") ;
		
		Iterator<WTPart> ite = parts.iterator() ;
		while( ite.hasNext() ){
			WTPart part = ite.next() ;
			
			if( part != null ){
				if(WorkInProgressHelper.isCheckedOut( part )){
					checkoutInfo.append(part.getNumber()) ;
					checkoutInfo.append(" , " ) ;
					checkoutInfo.append(part.getViewName()) ;
					checkoutInfo.append(" , " ) ;
					checkoutInfo.append(CommonPDMUtil.getVersion(part)) ;
					checkoutInfo.append("\n") ;
				}
			}
		}
		
		if( checkoutInfo.length() > 0 ){
			throw new WTException("以下零部件被检出：\n" + checkoutInfo.toString());
		}
	}
	
	
	public static List<WTPart> getAllSubPartsWithSubstitute(WTPart part){
		
		List<WTPart> partList = new ArrayList<WTPart>() ;

		List<WTPart> subPartList = new ArrayList<WTPart>() ;
		
		if( part == null ){
			return  subPartList ;
		}
		
		partList.add(part);
		
		//构造Map，通过编号过滤重复的零部件
		Map<String,WTPart> partNumberMap = new HashMap<String,WTPart>() ;
		
		try {			
			while( partList != null && partList.size() > 0 ){
				List<WTPart> tempPartList = new ArrayList<WTPart>() ;
				
				Iterator<WTPart> ite = partList.iterator() ;
				
				while( ite.hasNext() ){
					WTPart aPart = ite.next() ;
					
					List<WTPartUsageLink> usageLinkList = BOMStructureUtil.getFirstLevelUsageLink( aPart ) ;
					
					if( usageLinkList != null ){
						Iterator<WTPartUsageLink> usageLinkListIte = usageLinkList.iterator() ;
						
						while( usageLinkListIte.hasNext() ){
							WTPartUsageLink aUsageLink = usageLinkListIte.next() ;
							
							if( aUsageLink != null ){
								WTPart parentPart = aUsageLink.getUsedBy() ;
								WTPartMaster childPartMaster = aUsageLink.getUses() ;
								
								WTPart childPart = CoreUtil.getWTPartByMasterAndView( childPartMaster , parentPart.getViewName() ) ;
								
								addPart(partNumberMap, tempPartList,childPart);
								
								List<WTPart> substitutePartList = getSubstituteLink( aUsageLink ) ;
								
								Iterator<WTPart> substitutePartListIte = substitutePartList.iterator() ;
								while( substitutePartListIte.hasNext() ){
									WTPart substitutePart = substitutePartListIte.next() ;
									
									addPart(partNumberMap, tempPartList,substitutePart);
								}
							}
						}
					}
				}
				
				partList = tempPartList ;
			}
		} catch (ConfigException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
		
		subPartList.addAll( partNumberMap.values() );
		
		return subPartList ;
	}

	private static void addPart(Map<String, WTPart> partNumberMap,List<WTPart> tempPartList, WTPart aPart) {
		if( aPart != null ){
			String aPartNumber = aPart.getNumber() ;
			
			if( ! partNumberMap.containsKey( aPartNumber ) ){
				tempPartList.add(  aPart  ) ;
				
				partNumberMap.put( aPartNumber ,  aPart ) ;
			}
		}
	}
	
	/**
	 * 获取Part的特定替代件列表
	 * 
	 * 
	 * @param part WTPart 添加的对象
	 * @param usageLink WTPartUsageLink 添加的对象
	 * 
	 * @return List 特定替代件列表
	 * <b>Revision History</b> <br>
	 * <b>Rev:</b> 1.0 - 2012-07-12，魏文杰 <br>
	 * <b>Comment:</b> Initial release.
	 */
	public static List<WTPart> getSubstituteLink(WTPartUsageLink usageLink){
		
		List<WTPart> substituteList = new ArrayList<WTPart>() ;
		
		//这个获取特定替换部件
		if( usageLink != null ){
			try {
				WTPart parentPart = usageLink.getUsedBy();

				//获取usageLink上的所有特定替代关系
				WTCollection wtcol = WTPartHelper.service.getSubstituteLinks( usageLink ) ;
				
				if(wtcol != null){										
					Iterator ite = wtcol.iterator() ;
					
					while( ite.hasNext()){
						Object obj = ite.next() ;
						
						if( obj != null && obj instanceof ObjectReference){
							ObjectReference objRef = ( ObjectReference ) obj ;
							
							Object tempObj = objRef.getObject() ;
							
							if(tempObj != null && tempObj instanceof WTPartSubstituteLink ){
								WTPartSubstituteLink substituteLink = (WTPartSubstituteLink) tempObj ;

								WTPartMaster substitutePartMaster = substituteLink.getSubstitutes() ;
								
								//按照父件视图获取替代零部件对象
								WTPart substitutePart = CoreUtil.getWTPartByMasterAndView( substitutePartMaster , parentPart.getViewName() ) ;
								
								if( substitutePart != null ){
									substituteList.add( substitutePart ) ;
								}
							}
						}
					}
				}
			} catch (WTException e) {
				e.printStackTrace();
			}
		}
		
		return substituteList ;
	}
	
	private static void checkAllParts( List<WTPart> allPart , WTArrayList reviewObjs , WTArrayList inconformityReviewObjs ) {
		Iterator<WTPart> ite = allPart.iterator() ;
		
		while( ite.hasNext() ){
			WTPart part = ite.next() ;
			
			checkPartStatus( part , reviewObjs , inconformityReviewObjs ) ;
			
//			if( isRawMaterial( part ) ){
//				
//				//处理原材料
//				checkRawMaterial( part , reviewObjs , tableData );
//				
//			}else if( isSemiFinishedGood( part ) ) {
//				
//				//处理半成品
//				checkSemiFinishedGood( part , reviewObjs , tableData );
//				
//			}else if( isFinishedGood( part ) ) {
//				
//				//处理成品
//				checkFinishedGood( part , reviewObjs , tableData );
//				
//			}
		}
	}
	
	private static void checkPartStatus( WTPart part , WTArrayList reviewObjs , WTArrayList inconformityReviewObjs ){
		String currentState = part.getLifeCycleState().toString() ;
		
		System.out.println("当前对象【"+ part.getDisplayIdentifier()+"】的生命周期是："+currentState);
		
		//如果零部件状态为新品，批准和量产发布，则不处理
		if(currentState.equals(NEW_PRODUCT) || currentState.equals(APPROVAL)||currentState.equals(MASS_PRODUCTION_RELEASE)){
			
		}
		//如果零部件状态为正在工作
		else if( currentState.equals( INWORK ) ){
			reviewObjs.add( part ) ;
			checkPartDesignSate( part , reviewObjs , inconformityReviewObjs );			
		}
		// 如果零部件生命周期状态为其他状态，则记录到不合格列表中
		else{		
			inconformityReviewObjs.add( part );		
		}
	}
	
	/**
	 * 如果一个对象寄存在随迁列表中又存在不符合列表中则从不符合列表中清空该对象
	 * 
	 * 
	 * add kwang 2013-12-19
	 * @param reviewObjs
	 * @param inconformityReviewObjs
	 */
	public static WTArrayList chectWTArrayListIsContains( WTArrayList reviewObjs , WTArrayList  inconformityReviewObjs){
		WTArrayList inconList = new WTArrayList();		
		
		if( reviewObjs == null || inconformityReviewObjs == null ){
			return inconList;
		}
		
		inconList = inconformityReviewObjs;
		
		for( int i = 0 ; i <  inconformityReviewObjs.size() ; i++ ){
			Object inconObject = inconformityReviewObjs.get( i );
			
			if( inconObject != null && inconObject instanceof ObjectReference ){
				ObjectReference orf = ( ObjectReference )inconObject;
				
				inconObject = orf.getObject();
			}
			
			if( inconObject != null && inconObject instanceof WTPart ){
				
				WTPart inconPart = ( WTPart )inconObject;
				
				try {
					
					inconPart = CoreUtil.getWTPartByNumberAndView( inconPart.getNumber() , inconPart.getViewName() );
					
					for (int j = 0; j < reviewObjs.size() ; j++) {
						Object reviewObject = reviewObjs.get( j );
						
						if( reviewObject != null && reviewObject instanceof ObjectReference ){
							ObjectReference obrf = ( ObjectReference )reviewObject;
							
							reviewObject = obrf.getObject();
						}
						
						if( reviewObject != null && reviewObject instanceof WTPart ){
							WTPart reviewPart = ( WTPart )reviewObject;
							
							reviewPart = CoreUtil.getWTPartByNumberAndView( reviewPart.getNumber() , reviewPart.getViewName() );						
							
							if( inconPart.equals( reviewPart ) ){
								inconList.remove( inconObject );
								break;
							}													
						}						
					}	
					
				} catch (WTException e) {
					e.printStackTrace();
				}
				
			}
		}
		System.out.println( "Debug   返回值大小：" + inconList.size() );
		return inconList;
	}
	
	/**
	 * 获取零部件“Design”视图对象，如果“Design”视图对象状态为“正在工作”状态添加到随迁列表中
	 * 
	 * BOM审核流程
	 * 
	 * @param part
	 * @param reviewObjs
	 * @param inconformityReviewObjs
	 */
	public static void checkPartDesignSate( WTPart part , WTArrayList reviewObjs , WTArrayList inconformityReviewObjs ){
		
		if( part == null ){
			return;
		}
		
		if( TMTypeUtil.isSemiFinishedGood( part ) || TMTypeUtil.isRawMaterial( part ) || TMTypeUtil.isFinishedGood( part ) ){
			
			try {
				
				WTPart designPart = CoreUtil.getWTPartByNumberAndView( part.getNumber() , D_VIEWS );
				
				if( designPart != null ){
					State state = designPart.getLifeCycleState();
					
					if( state != null ){
						String partState = state.toString();
						if( partState.equals( INWORK ) ){
							reviewObjs.add( designPart );
						}else if( !list.contains( partState ) ){
							inconformityReviewObjs.add( designPart );
						}
					}
				}
			} catch (WTException e) {
				e.printStackTrace();
			}
		}
	}
}
